package com.showmaker.controller;

import com.showmaker.constant.MessageConstant;
import com.showmaker.entity.Result;
import com.showmaker.service.MemberService;
import com.showmaker.service.ReportService;
import com.showmaker.service.SetmealService;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/report")
public class ReportController {

    @DubboReference(interfaceClass = MemberService.class, version = "1.0")
    private MemberService memberService;

    @DubboReference(interfaceClass = SetmealService.class, version = "1.0")
    private SetmealService setmealService;

    @DubboReference(interfaceClass = ReportService.class, version = "1.0")
    private ReportService reportService;

    /**
     * 会员信息折线图
     * @return 返回折线图需要的数据
     */
    @RequestMapping("/getMemberReport")
    public Result getMemberReport() {
        Map<String, Object> map = new HashMap<>();

        try {
            // 保存当前时间到一年前的字符串
            List<String> months = new ArrayList<>();
            Calendar calendar = Calendar.getInstance();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
            calendar.add(Calendar.MONTH, -12);
            for (int i = 1; i <= 12; i++) {
                calendar.add(Calendar.MONTH, 1);
                Date date = calendar.getTime();
                months.add(sdf.format(date));
            }

            // 查询月份对应的会员人数
            List<Integer> memberCount = memberService.findMemberCountByMonths(months);

            // 将月份和人数封装成一个map集合
            map.put("months", months);
            map.put("memberCount", memberCount);
        } catch (Exception e) {
            return new Result(false, MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL);
        }

        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, map);
    }

    /**
     * 获取套餐统计数据(饼状图)
     * @return 返回套餐统计数据
     */
    @GetMapping("/getSetmealReport")
    public Result getSetmealReport() {
        HashMap<String, Object> map = new HashMap<>();

        try {
            // 获取套餐的名称及其对应的数据
            List<Map<String, Object>> setmealCount = setmealService.getSetmealCount();
            map.put("setmealCount", setmealCount);

            // 获取所有的套餐名称
            ArrayList<String> setmealNames = new ArrayList<>();
            for (Map<String, Object> setmeal : setmealCount) {
                setmealNames.add((String) setmeal.get("name"));
            }
        } catch (Exception e) {
            return new Result(false, MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL);
        }

        return new Result(true, MessageConstant.GET_SETMEAL_LIST_SUCCESS, map);
    }

    /**
     * 运营统计数据(数据表单)
     * @return 返回运营统计数据
     */
    @RequestMapping("/getBusinessReportData")
    public Result getBusinessReportData() {
        try {
            Map<String, Object> data = reportService.getBusinessReportData();
            return new Result(true, MessageConstant.GET_BUSINESS_REPORT_SUCCESS, data);
        } catch (Exception e) {
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_SUCCESS);
        }
    }

    /**
     * 将数据导出为Excel文件
     * @param response 使用 response 将数据返回给浏览器
     */
    @RequestMapping("/exportBusinessReport")
    public void exportBusinessReport(HttpServletResponse response) {
        Map<String, Object> result = reportService.getBusinessReportData();
        try {
            //取出返回结果数据，准备将报表数据写入到Excel文件中
            String reportDate = (String) result.get("reportDate");
            Integer todayNewMember = (Integer) result.get("todayNewMember");
            Integer totalMember = (Integer) result.get("totalMember");
            Integer thisWeekNewMember = (Integer) result.get("thisWeekNewMember");
            Integer thisMonthNewMember = (Integer) result.get("thisMonthNewMember");
            Integer todayOrderNumber = (Integer) result.get("todayOrderNumber");
            Integer thisWeekOrderNumber = (Integer) result.get("thisWeekOrderNumber");
            Integer thisMonthOrderNumber = (Integer) result.get("thisMonthOrderNumber");
            Integer todayVisitsNumber = (Integer) result.get("todayVisitsNumber");
            Integer thisWeekVisitsNumber = (Integer) result.get("thisWeekVisitsNumber");
            Integer thisMonthVisitsNumber = (Integer) result.get("thisMonthVisitsNumber");
            List<Map<String, Object>> hotSetmeal = (List<Map<String, Object>>) result.get("hotSetmeal");

            // 读取 Excel 文件
            File file = ResourceUtils.getFile("classpath:static/template/report_template.xlsx");
            XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(file));

            XSSFSheet sheet = workbook.getSheetAt(0);

            XSSFRow row = sheet.getRow(2);
            row.getCell(5).setCellValue(reportDate);//日期

            row = sheet.getRow(4);
            row.getCell(5).setCellValue(todayNewMember);//新增会员数（本日）
            row.getCell(7).setCellValue(totalMember);//总会员数

            row = sheet.getRow(5);
            row.getCell(5).setCellValue(thisWeekNewMember);//本周新增会员数
            row.getCell(7).setCellValue(thisMonthNewMember);//本月新增会员数

            row = sheet.getRow(7);
            row.getCell(5).setCellValue(todayOrderNumber);//今日预约数
            row.getCell(7).setCellValue(todayVisitsNumber);//今日到诊数

            row = sheet.getRow(8);
            row.getCell(5).setCellValue(thisWeekOrderNumber);//本周预约数
            row.getCell(7).setCellValue(thisWeekVisitsNumber);//本周到诊数

            row = sheet.getRow(9);
            row.getCell(5).setCellValue(thisMonthOrderNumber);//本月预约数
            row.getCell(7).setCellValue(thisMonthVisitsNumber);//本月到诊数

            int rowNum = 12;

            for(Map map : hotSetmeal){//热门套餐
                String name = (String) map.get("name");
                Long setmeal_count = (Long) map.get("setmeal_count");
                BigDecimal proportion = (BigDecimal) map.get("proportion");
                row = sheet.getRow(rowNum++);
                row.getCell(4).setCellValue(name);//套餐名称
                row.getCell(5).setCellValue(setmeal_count);//预约数量
                row.getCell(6).setCellValue(proportion.doubleValue());//占比
            }

            //通过输出流进行文件下载
            ServletOutputStream out = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-Disposition", "attachment;filename=report.xlsx");
            workbook.write(out);

            out.flush();
            out.close();
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/exportBusinessReport4PDF")
    public void exportBusinessReport4PDF(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = reportService.getBusinessReportData();
        try {
            //取出返回结果数据
            List<Map<String, Object>> hotSetmeal = (List<Map<String, Object>>) result.get("hotSetmeal");

            // 读取 PDF 模版文件
            String jrxmlPath = ResourceUtils.getFile("classpath:static/template/health_business.jrxml").getPath();
            System.out.println(jrxmlPath.lastIndexOf("\\") + 1);
            String jasperPath = jrxmlPath.substring(0, jrxmlPath.lastIndexOf("\\") + 1) + "health_business.jasper";

            System.out.println("jrxmlPath = " + jrxmlPath);
            System.out.println("jasperPath = " + jasperPath);

            // 编译模版文件
            JasperCompileManager.compileReportToFile(jrxmlPath, jasperPath);

            // 填充数据
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperPath, result, new JRBeanCollectionDataSource(hotSetmeal));

            //通过输出流进行文件下载
            ServletOutputStream out = response.getOutputStream();
            response.setContentType("application/pdf");
            response.setHeader("content-Disposition", "attachment;filename=report.pdf");

            //输出文件
            JasperExportManager.exportReportToPdfStream(jasperPrint, out);

            out.flush();
            out.close();
        } catch (IOException | JRException e) {
            e.printStackTrace();
        }
    }
}
